package cur.nature.component.redis.common;

import cur.nature.framework.core.util.JsonUtil;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import cur.nature.component.redis.guava.NoVlaInGauvaException;
import cur.nature.framework.core.log.LOG;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class LocalCacheUtil {

    private static LoadingCache<String,Object> cache = CacheBuilder.newBuilder().maximumSize(1000)
            .build(new CacheLoader<String, Object>() {
                @Override
                public Object load(String key) throws Exception {
                    final Object value = RedisUtil.get(key);
                    if (value != null) {
                        return value;
                    }
                    throw new NoVlaInGauvaException("null value");
                }
            });

    public static Object get(String key){
        try {
            return cache.getUnchecked(key);
        } catch (Exception ex) {
            if (ex instanceof NoVlaInGauvaException) {
                LOG.error("null value",ex);
            }
        }
        return null;
    }

    public static <T> T get(String key, Class<T> clazz){
        final Object obj = get(key);
        return obj == null ? null : (T) obj;
    }

    public static String getStr(String key){
        final Object obj = get(key);
        return obj == null ? null : obj.toString();
    }

    public static <T> List<T> getList(String key, Class<T> clazz){
        final Object obj = get(key);
        if (obj != null && obj instanceof String) {
            List<T> list = JsonUtil.parseArray(obj.toString(), clazz);
            return list;
        }
        return obj == null ? null : (List<T>) obj;
    }

    public static <T> Set<T> getSet(String key, Class<T> clazz){
        final Object obj = get(key);
        if (obj != null && obj instanceof String) {
            List<T> list = JsonUtil.parseArray(obj.toString(), clazz);
            return new HashSet<T>(list);
        } else if (obj != null && obj instanceof ArrayList) {
            return new HashSet<T>((Collection<? extends T>) obj);
        }
        return obj == null ? null : (Set<T>) obj;
    }

    public static Map getMap(String key){
        final Object obj = get(key);
        if (obj != null && obj instanceof String) {
            Map map = JsonUtil.parseObject(obj.toString(), Map.class);
            return map;
        }
        return obj == null ? null : (Map) obj;
    }

    public static void put(String key,Object value){
        cache.put(key,value);
    }

}
